package com.weixin.servlet;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.weixin.entity.Goods;
import com.weixin.entity.HouseGoods;
import com.weixin.entity.Purchase;
import com.weixin.entity.Purchase_people;
import com.weixin.entity.Storehouse;
import com.weixin.entity.Supplier;
import com.weixin.service.IGoodsService;
import com.weixin.service.IHouseGoodsService;
import com.weixin.service.IPurchaseService;
import com.weixin.service.IPurchase_peopleService;
import com.weixin.service.IStorehouseService;
import com.weixin.service.ISupplierService;
import com.weixin.service.impl.GoodsServiceImpl;
import com.weixin.service.impl.HouseGoodsServiceImpl;
import com.weixin.service.impl.PurchaseServiceImpl;
import com.weixin.service.impl.Purchase_peopleServiceImpl;
import com.weixin.service.impl.StorehouseServiceImpl;
import com.weixin.service.impl.SupplierServiceImpl;
import com.weixin.util.PageSizeUtil;

@WebServlet("/PurchaseServlet/*")
public class PurchaseServlet extends HttpServlet {
	 private static Logger logger = Logger.getLogger(PurchaseServlet.class); 
	IPurchaseService purchase_service=new PurchaseServiceImpl();
	IGoodsService goods_service=new GoodsServiceImpl();
	IPurchase_peopleService people_service=new Purchase_peopleServiceImpl();
	ISupplierService supplier_servie=new SupplierServiceImpl();
	IStorehouseService storehouseService=new StorehouseServiceImpl();
	IHouseGoodsService housegoodsService=new HouseGoodsServiceImpl();
	
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String path = request.getPathInfo().substring(1);
		if("list".equals(path)){
			getList(request,response);
		}else if("deleteInfo".equals(path)){
			DeleteInfo(request,response);
		}else if("addInfo".equals(path)){
			AddInfo(request,response);
		}else if("preEditInfo".equals(path)){
			PreEditInfo(request,response);
		}else if("editInfo".equals(path)){
			EditInfo(request,response);
		}else if("inspectInfo".equals(path)){
			InspectInfo(request,response);
			//处理审核业务
		}else if("inspectInfoList".equals(path)){
			//显示要审核信息
			InspectInfoList(request,response);
		}else if("noInspectInfo".equals(path)){
			//取消审核
			NoInspectInfo(request,response);
		}else if("noInStroehouseList".equals(path)){
			//显示审核后但未入库的信息
			NoInStroehouseList(request,response);
		}else if("chooseStorehouseList".equals(path)){
			//显示仓库信息，用来选择仓库
			ChooseStorehouseList(request,response);
		}else if("inStorehouse".equals(path)){
			//采购入库
			InStorehouse(request,response);
		}else if("findPurchseInfo".equals(path)){
			//得到审核且入库的采购信息
			FindPurchseInfo(request,response);
		}else if("findByCondition".equals(path)){
			//得到审核且入库的采购信息
			FindByCondition(request,response);
		}else if("selectLikeValuesList".equals(path)){
			//模糊查询,采购管理页
			SelectLikeValuesList(request,response);
		}
	}
	

	private void SelectLikeValuesList(HttpServletRequest request, HttpServletResponse response) {
		String values = request.getParameter("values");
		
		try {
			List<Purchase> purchase_list = purchase_service.getAllAboutLike(values);
			request.setAttribute("purchase_list",purchase_list);
			

			//添加采购计划中下拉框所需信息，商品名，采购人，厂商
			List<Goods> goods_list = goods_service.getAll();
			List<Purchase_people> people_list = people_service.selectAll();
			List<Supplier> supplier_list = supplier_servie.selectAll();
			
			request.setAttribute("goods_list",goods_list);
			request.setAttribute("people_list",people_list);
			request.setAttribute("supplier_list",supplier_list);
			
			request.getRequestDispatcher("/page/user/purchase/purchaseManage.jsp").forward(request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	private void FindByCondition(HttpServletRequest request, HttpServletResponse response) {
		Map<String, String[]> parameterMap = request.getParameterMap();
		try {
			List<Purchase> purchaseList = purchase_service.getByCondition(parameterMap);
			request.setAttribute("purchaseList",purchaseList);
			request.getRequestDispatcher("/page/user/purchase/selectPurchaseInfo.jsp").forward(request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void FindPurchseInfo(HttpServletRequest request, HttpServletResponse response) {
		int pageNum=Integer.valueOf(request.getParameter("pageNum"));
		try {
			//采购数据
			List<Purchase> purchaseList = purchase_service.getInStroehouse(PageSizeUtil.PAGE_SIZE,pageNum);
			request.setAttribute("purchaseList",purchaseList);
			
			//分页条数据
			request.setAttribute("pageCount", Math.ceil(purchase_service.getInStorehouseTotal()*1.0/PageSizeUtil.PAGE_SIZE));
			request.setAttribute("pageNum", pageNum);
			
			request.getRequestDispatcher("/page/user/purchase/selectPurchaseInfo.jsp").forward(request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	private void InStorehouse(HttpServletRequest request, HttpServletResponse response) {
		int storehouse_id=Integer.valueOf(request.getParameter("storehouse_id"));
		int purchase_id=Integer.valueOf(request.getParameter("purchase_id"));
		
		boolean isOk=false;//用来记录是否在库存商品表中添加成功
		
		try {
			Purchase purchase = purchase_service.selectById(purchase_id);
			purchase.setStorehouse_id(storehouse_id);
			purchase.setPurchase_time(new Date());
			
			//先查看库存中是否有改商品，有的话在原有基础上添加，没有的话添加新的库存商品
			int goods_id=Integer.valueOf(purchase.getGoods_id());//得到要入库的商品id
			HouseGoods housegoods = housegoodsService.selectByGoodsId(goods_id);
			if(housegoods!=null) {
				//仓库有该商品
				housegoods.setNumber(housegoods.getNumber()+purchase.getNumber());//库存商品数量加上采购商品数量
				//得到商品价格
				Double price=goods_service.selectById(goods_id).getPrice();
				housegoods.setSum(housegoods.getSum()+purchase.getNumber()*price);//总金额				
				isOk=housegoodsService.updateHGoods(housegoods);		
			}else {
				//仓库没有该商品
				HouseGoods newhousegoods=new HouseGoods();
				newhousegoods.setGoods_id(goods_id);
				newhousegoods.setNumber(purchase.getNumber());
				//得到商品价格
				Double price=goods_service.selectById(goods_id).getPrice();
				
				newhousegoods.setSum(purchase.getNumber()*price);
				newhousegoods.setStorehouse_id(storehouse_id);
				isOk=housegoodsService.insertHGoods(newhousegoods);
				
			}
			if(purchase_service.updatePurchase(purchase)&&isOk) {
				logger.error("商品入库："+purchase);
				response.getWriter().print(1);
			}else {
				response.getWriter().print(0);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error(e);
		}
	}

	private void ChooseStorehouseList(HttpServletRequest request, HttpServletResponse response) {
		String purchase_id=request.getParameter("purchase_id");
		try {
			List<Storehouse> storehouseList = storehouseService.selectAll();
			request.setAttribute("storehouseList",storehouseList);
			request.setAttribute("purchase_id",purchase_id);
			request.getRequestDispatcher("/page/user/purchase/chooseStorehouseForm.jsp").forward(request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	private void NoInStroehouseList(HttpServletRequest request, HttpServletResponse response) {
		try {
			int pageNum =Integer.valueOf(request.getParameter("pageNum"));
			try {
				
				//获取审核之后要入库的采购信息
				List<Purchase> purchase_list = purchase_service.getInspect(PageSizeUtil.PAGE_SIZE1,pageNum);
				request.setAttribute("purchase_list",purchase_list);

				//分页条需要的数据
				request.setAttribute("pageCount",Math.ceil(purchase_service.getInspectTotal()*1.0/PageSizeUtil.PAGE_SIZE1));
				request.setAttribute("pageNum",pageNum);
				
				request.getRequestDispatcher("/page/user/purchase/inStoreHouse.jsp").forward(request, response);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
		} catch (Exception e) {
			String values = request.getParameter("values");
			try {
				List<Purchase> purchase_list = purchase_service.getLikeForInHouse(values);
				request.setAttribute("purchase_list",purchase_list);
				request.getRequestDispatcher("/page/user/purchase/inStoreHouse.jsp").forward(request, response);
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		
	}

	private void NoInspectInfo(HttpServletRequest request, HttpServletResponse response) {
		int purchase_id =Integer.valueOf(request.getParameter("purchase_id"));		
		try {
			Purchase purchase = purchase_service.selectById(purchase_id);
			purchase.setInspect(0);
			if(purchase_service.updatePurchase(purchase)) {
				response.getWriter().print(1);
			}else {
				response.getWriter().print(0);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	private void InspectInfo(HttpServletRequest request, HttpServletResponse response) {
		int purchase_id =Integer.valueOf(request.getParameter("purchase_id"));	
		try {
			Purchase purchase = purchase_service.selectById(purchase_id);
			purchase.setInspect(1);
			if(purchase_service.updatePurchase(purchase)) {
				logger.error("审核商品：purchase_id="+purchase_id);
				response.getWriter().print(1);
			}else {
				response.getWriter().print(0);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error(e);
		}
	}

	private void InspectInfoList(HttpServletRequest request, HttpServletResponse response) {	
		//使用try/catch处理不同请求
		try {
			int pageNum =Integer.valueOf(request.getParameter("pageNum"));
			try {
				//获取要审核采购信息
				List<Purchase> purchase_list= purchase_service.get_all_about(PageSizeUtil.PAGE_SIZE2,pageNum);
				System.out.println(purchase_list);
				request.setAttribute("purchase_list",purchase_list);

				//分页需要的数据
				request.setAttribute("pageCount",Math.ceil(purchase_service.get_all_aboutTotal()*1.0/PageSizeUtil.PAGE_SIZE2));
				request.setAttribute("pageNum",pageNum);
				request.getRequestDispatcher("/page/user/purchase/inspectPurchase.jsp").forward(request, response);
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}catch(Exception e){
			String values = request.getParameter("values");
			try {
				List<Purchase> purchase_list=purchase_service.getAllAboutLike(values);
				request.setAttribute("purchase_list",purchase_list);
				request.getRequestDispatcher("/page/user/purchase/inspectPurchase.jsp").forward(request, response);	
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
		}	
	}


	private void EditInfo(HttpServletRequest request, HttpServletResponse response) {	
		int purchase_id=Integer.valueOf(request.getParameter("purchase_id"));
		int goods_id=Integer.valueOf(request.getParameter("goods_id"));
		Double price=Double.parseDouble(request.getParameter("price"));
		String unit=request.getParameter("unit");
		int number=Integer.valueOf(request.getParameter("number"));
		int people_id=Integer.valueOf(request.getParameter("purchase_people_id"));
		int supplier_id=Integer.valueOf(request.getParameter("supplier_id"));
		String remark=request.getParameter("remark");
		//System.out.println(purchase_id);
		//System.out.println("要修改的数据:"+goods_id+"/"+price+"/"+unit+"/"+number+"/"+people_id+"/"+supplier_id+"/"+remark);
		
		try {
			Purchase purchase = purchase_service.selectById(purchase_id);
			purchase.setGoods_id(goods_id);
			purchase.setNumber(number);
			purchase.setPurchase_people_id(people_id);
			purchase.setSupplier_id(supplier_id);
			purchase.setRemark(remark);
			
			Goods goods = goods_service.selectById(goods_id);
			goods.setPrice(price);
			goods.setUnit(unit);
			
			if(purchase_service.updatePurchase(purchase)&&goods_service.updateGoods(goods)){
				logger.error("采购更改：purchase="+purchase+"/goods"+goods);
				response.getWriter().print(1);
			}else{
				response.getWriter().print(0);
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error(e);
		}
		
	}

	private void PreEditInfo(HttpServletRequest request, HttpServletResponse response) {
		int purchase_id=Integer.valueOf(request.getParameter("purchase_id"));
		//System.out.println("准备要删除了哈，编号是："+purchase_id);
		try {
			//添加采购计划中下拉框所需信息，商品名，采购人，厂商
			List<Goods> goods_list = goods_service.getAll();
			List<Purchase_people> people_list = people_service.selectAll();
			List<Supplier> supplier_list = supplier_servie.selectAll();
			
			request.setAttribute("goods_list",goods_list);
			request.setAttribute("people_list",people_list);
			request.setAttribute("supplier_list",supplier_list);
			
			//得到要修改的采购信息
			Purchase purchase = purchase_service.getAllAboutById(purchase_id);
			request.setAttribute("purchase",purchase);
			
//			System.out.println(supplier_list);
//			System.out.println(purchase);
			
			request.getRequestDispatcher("/page/user/purchase/editPurchase.jsp").forward(request, response);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	private void AddInfo(HttpServletRequest request, HttpServletResponse response) {
		int goods_id =Integer.valueOf(request.getParameter("goods_id"));
		Double price =Double.parseDouble(request.getParameter("price"));
		String unit = request.getParameter("unit");
		int number =Integer.valueOf(request.getParameter("number"));
		int purchase_people_id =Integer.valueOf(request.getParameter("purchase_people_id"));
		int supplier_id=Integer.valueOf(request.getParameter("supplier_id"));
		String remark = request.getParameter("remark");
		
		Purchase purchase=new Purchase();
		purchase.setGoods_id(goods_id);
		purchase.setNumber(number);
		purchase.setPurchase_people_id(purchase_people_id);
		purchase.setSupplier_id(supplier_id);
		purchase.setRemark(remark);
		purchase.setStorehouse_id(10);
		
		
		try {
			Goods goods = goods_service.selectById(goods_id);
			goods.setPrice(price);
			goods.setUnit(unit);
			boolean isok = goods_service.updateGoods(goods);
			
			if(purchase_service.insertPurchase(purchase)&&isok) {
				logger.error("添加采购：purchase="+purchase);
				request.setAttribute("addmsg","添加成功");
				request.getRequestDispatcher("/PurchaseServlet/list?pageNum=1").forward(request, response);
			}else {
				request.setAttribute("addmsg","添加失败");
				request.getRequestDispatcher("/PurchaseServlet/list?pageNum=1").forward(request, response);
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error(e);
		}
		
	}

	private void DeleteInfo(HttpServletRequest request, HttpServletResponse response) {
			int purchase_id =Integer.valueOf(request.getParameter("purchase_id"));
			//System.out.println("要删除的采购id"+purchase_id);
			try {				
				if(purchase_service.deleteById(purchase_id)) {
					logger.error("伪删除采购信息，purchase_id="+purchase_id);
					response.getWriter().print("1");
				}else {
					response.getWriter().print("0");
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				logger.error(e);
			}
	}

	private void getList(HttpServletRequest request, HttpServletResponse response) {
		int pageNum=Integer.valueOf(request.getParameter("pageNum"));
		try {
			//获取采购列表信息
			List<Purchase> purchase_list = purchase_service.get_all_about(PageSizeUtil.PAGE_SIZE3,pageNum);
			System.out.println(purchase_list);
			request.setAttribute("purchase_list",purchase_list);
			
			//分页条需要的数据
			request.setAttribute("pageCount",Math.ceil(purchase_service.get_all_aboutTotal()*1.0/PageSizeUtil.PAGE_SIZE3));
			request.setAttribute("pageNum",pageNum);
			
			//添加采购计划中下拉框所需信息，商品名，采购人，厂商
			List<Goods> goods_list = goods_service.getAll();
			List<Purchase_people> people_list = people_service.selectAll();
			List<Supplier> supplier_list = supplier_servie.selectAll();
			
			request.setAttribute("goods_list",goods_list);
			request.setAttribute("people_list",people_list);
			request.setAttribute("supplier_list",supplier_list);
			
			request.getRequestDispatcher("/page/user/purchase/purchaseManage.jsp").forward(request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}


}
